import React, { useContext, useEffect, useRef, useState } from 'react';
import {
  Input,
  Card,
  List,
  Modal,
  Form,
  FormInstance,
  Notification,
  Popconfirm,
} from '@arco-design/web-react';
import { GlobalContext } from '@/context';
import locale from './locale';
import useLocale from '@/utils/useLocale';
import { IconDelete, IconEdit, IconPlus } from '@arco-design/web-react/icon';
import Title from '@arco-design/web-react/es/Typography/title';
import {
  addDictGroup,
  getDictGroupInfo,
  removeDictGroup,
  searchList,
  updateDictGroup,
} from '@/api/dict';
import FormItem from '@arco-design/web-react/es/Form/form-item';
import PermissionWrapper from '@/components/PermissionWrapper';

function DictGroup(props: { callback: (record: any, type: any) => void }) {
  const { lang } = useContext(GlobalContext);

  const addFormRef = useRef<FormInstance>();
  const updateFormRef = useRef<FormInstance>();

  const [loading, setLoading] = React.useState(false);

  const t = useLocale(locale);

  // 点击行
  const [clickItem, setClickItem] = useState(null);

  function onClickItem(id) {
    props.callback(id, 'onClickGroup');
    setClickItem(id);
  }

  //添加

  const [addVisible, setAddVisible] = useState(false);
  function addData() {
    setAddVisible(true);
  }

  function addDataConfirm() {
    addFormRef.current.validate().then((values) => {
      setLoading(true);
      addDictGroup(values)
        .then((res) => {
          const { success, message } = res.data;
          if (success) {
            Notification.success({ content: message, duration: 1000 });
            setAddVisible(false);
            fetchData();
          }
        })
        .finally(() => {
          setLoading(false);
        });
    });
  }

  //编辑
  const [updateVisible, setUpdateVisibled] = useState(false);
  function updateData(id) {
    getDictGroupInfo(id).then((res) => {
      const { success, data } = res.data;
      if (success) {
        updateFormRef.current.setFieldsValue(data);
      }
    });
    setUpdateVisibled(true);
  }

  function updateDataConfirm() {
    updateFormRef.current.validate().then((values) => {
      setLoading(true);
      values.default = false;
      updateDictGroup(values)
        .then((res) => {
          const { success, message } = res.data;
          if (success) {
            Notification.success({ content: message, duration: 1000 });
            setUpdateVisibled(false);
            fetchData();
          }
        })
        .finally(() => {
          setLoading(false);
        });
    });
  }

  //删除
  function deleteData(id) {
    removeDictGroup(id)
      .then((res) => {
        const { success, message } = res.data;
        if (success) {
          Notification.success({ content: message, duration: 1000 });
        } else {
          Notification.error({ content: message, duration: 1000 });
        }
      })
      .finally(() => fetchData());
  }

  const [dictGroupList, setDictGroupList] = useState([]);

  function fetchData(group_name?: string) {
    const param = {
      group_name: undefined,
      page_data: {
        page: 0,
        page_size: 0,
      },
    };
    if (group_name) {
      param.group_name = group_name;
    }
    searchList(param).then((res) => {
      const { success, data } = res.data;
      if (success) {
        if (data.length > 0) {
          onClickItem(data[0].id);
        }
        setDictGroupList(data);
      }
    });
  }

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <Card style={{ minHeight: '460px' }}>
      <Title heading={6}>{t['menu.group']}</Title>
      <Input.Search
        style={{ marginBottom: 16 }}
        allowClear
        searchButton
        onSearch={(value) => fetchData(value)}
      />
      <List
        loading={loading}
        header={[
          <PermissionWrapper
            key={'add'}
            requiredPermissions={[
              {
                resource: 'dict_group_manager',
                actions: ['api_dict_group_add'],
              },
            ]}
          >
            <span key={'plus'}>
              <IconPlus onClick={addData} />
            </span>
          </PermissionWrapper>,
        ]}
        size="small"
        dataSource={dictGroupList}
        render={(item, index) => (
          <List.Item
            onClick={() => onClickItem(item.id)}
            key={index}
            actions={[
              <PermissionWrapper
                key={'update'}
                requiredPermissions={[
                  {
                    resource: 'dict_group_manager',
                    actions: ['api_dict_group_update'],
                  },
                ]}
              >
                <span key={'edit'}>
                  <IconEdit onClick={() => updateData(item.id)} />
                </span>
              </PermissionWrapper>,
              <PermissionWrapper
                key={'delete'}
                requiredPermissions={[
                  {
                    resource: 'dict_group_manager',
                    actions: ['api_dict_group_delete'],
                  },
                ]}
              >
                <Popconfirm
                  focusLock
                  title={t['option.delete.confirm.title']}
                  onOk={() => {
                    deleteData(item.id);
                  }}
                >
                  <span key={'delete'}>
                    <IconDelete />
                  </span>
                </Popconfirm>
              </PermissionWrapper>,
            ]}
            style={{ background: clickItem == item.id ? '#F2F3F5' : '' }}
          >
            <List.Item />
            {item.group_name + '(' + item.group_code + ')'}
          </List.Item>
        )}
      />
      <Modal
        title={t['searchTable.operations.add']}
        visible={addVisible}
        onOk={() => {
          addDataConfirm();
        }}
        onCancel={() => {
          setAddVisible(false);
        }}
        autoFocus={false}
        focusLock={true}
        confirmLoading={loading}
      >
        <Form
          ref={addFormRef}
          style={{ width: '95%', marginTop: '6px' }}
          labelCol={{ span: lang === 'en-US' ? 7 : 6 }}
          wrapperCol={{ span: lang === 'en-US' ? 17 : 18 }}
        >
          <FormItem
            required
            label={t['searchTable.columns.group_name']}
            field={'group_name'}
          >
            <Input placeholder={t['searchForm.placeholder']} allowClear />
          </FormItem>
        </Form>
      </Modal>
      <Modal
        title={t['searchTable.update.title']}
        visible={updateVisible}
        onOk={() => {
          updateDataConfirm();
        }}
        onCancel={() => {
          setUpdateVisibled(false);
        }}
        autoFocus={false}
        focusLock={true}
        confirmLoading={loading}
      >
        <Form
          ref={updateFormRef}
          style={{ width: '95%', marginTop: '6px' }}
          labelCol={{ span: lang === 'en-US' ? 7 : 6 }}
          wrapperCol={{ span: lang === 'en-US' ? 17 : 18 }}
        >
          <FormItem field={'id'} hidden>
            <Input />
          </FormItem>
          <FormItem
            required
            label={t['searchTable.columns.group_name']}
            field={'group_name'}
          >
            <Input placeholder={t['searchForm.placeholder']} allowClear />
          </FormItem>
          <FormItem
            disabled
            label={t['searchTable.columns.group_code']}
            field={'group_code'}
          >
            <Input placeholder={t['searchForm.placeholder']} allowClear />
          </FormItem>
        </Form>
      </Modal>
    </Card>
  );
}

export default DictGroup;
